import {defineStore} from "pinia";
// @ts-ignore
import {ajax, requestCache} from "@/js/api_tool.js";
// @ts-ignore
import {cacheGet, cacheSet} from "@/store/pluginCache.js";

export const use_this_admin = defineStore('this_admin', {
    state: () => {
        return {
            id: 0,
            name: "",
            nickname: "",
            truename: "",
            admin_role_ids: "",
            is_agent: 0,
            phone: "",
            head_img: "",
            info: "",
            token: "",
            status: '',
            create_time: "",
            delete_time: 0,
            tenant_id: 0,
            rights: [],
            agent: {},
        }
    },
    actions: {
        /**通过请求接口，获取数据后合并，来刷新数据
         */
        async refresh(){
            try {
                let {data} = await ajax({url: '/admin/index/info', showMessage: ajax.SHOW_MESSAGE_NONE});
                if (!data){
                    // 未登陆的清空
                    return this.$reset();
                }
                let old = cacheGet(this.$id);
                const old_json = JSON.stringify(old);
                const data_json = JSON.stringify(data);
                if (old_json !== data_json){
                    console.log(`refresh ${this.$id} ok`)
                    this.$patch(data);
                    cacheSet(this.$id, data);
                }
            } catch (e:any) {
                console.log(`refresh fail: ${e.message || e}`)
            }
        },
    }
})
